<template>
    <div class="layout">
        <div class="title">
            <div class="title-label">
                <span class="title-label-text">群基础数据</span>
                <el-tooltip effect="dark" popper-class="group-statistics-desc-tootip" placement="top-start">
                    <template #content>
                        <ChartTootipDesc />
                    </template>
                    <span class="title-label-text-icon">
                        <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                    </span>
                </el-tooltip>
            </div>
            <div class="title-right">
                <el-date-picker
                    v-model="form.screen_time_range"
                    type="daterange"
                    :teleported="false"
                    :editable="false"
                    :clearable="false"
                    :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="—"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :disabled-date="disabledDate"
                    @change="handleTimeChange"
                    @calendar-change="calendarChange" />
            </div>
        </div>
        <el-row v-if="props.chartInfo.length" class="tab-list" :gutter="24">
            <el-col
                v-for="(item, index) in props.chartInfo"
                :key="item.field_key"
                class="tab-item"
                :class="{
                    'tab-item-active': item.field_key === form.selected_quota
                }"
                @click="onTabItem(item)">
                <div class="tab-item-card">
                    <div class="tab-item-content">
                        <div class="tab-item-name">{{ item.field_name }}</div>
                        <div class="tab-item-num">
                            <render-colunm-number :num="item.field_val" :unit="item.unit || '个'" />
                        </div>
                    </div>

                    <!-- 换行的方案 -->
                    <div v-if="index === props.chartInfo.length - 1" class="tab-item-more" @click.stop="onSelectColumn">
                        <div class="tab-item-more-circle">
                            <el-icon color="#ffffff" size="14"><ArrowRightBold /></el-icon>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <div class="chart_box">
            <div v-if="isShoweCharts" ref="myRef" class="chart_line"></div>
        </div>
        <el-empty v-if="!isShoweCharts" description="暂无数据"></el-empty>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, reactive, watch, nextTick, computed } from 'vue';
import { getCustomerGroupLineChart } from '@/api/dataCenter/customerGroupAnalysis/customerGroupData';

import { getDay } from '@/utils/utils';

import RenderColunmNumber from '@/components/zw/select-colunm-dialog/render-colunm-number.vue';

import ChartTootipDesc from './chart-tootip-desc.vue';
import dayjs from 'dayjs';

const echarts: any = inject('ec');

const props = withDefaults(
    defineProps<{
        chartInfo: Array<any>;
    }>(),
    {
        chartInfo: () => []
    }
);

const emit = defineEmits<{
    (e: 'select-column'): void;
    (e: 'change-date'): void;
}>();

const isShoweCharts = ref(false);
const xData = ref([]);
const yData = ref([]);
const myRef = ref(null);

const pickDay = ref();

// 上线时间为： 2023年7月12日, 7.10日之后可以选
const ONLINE_TIME = new Date(2023, 6, 10);

const form = reactive({
    // 默认的时间为最近7天，如果之前的时间小于上线日期，则默认为上线日的后一天～昨天
    screen_time_range: [
        +new Date(getDay(-7)) < +ONLINE_TIME
            ? dayjs(ONLINE_TIME).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
            : getDay(-7),
        getDay(-1, true)
    ],
    selected_quota: 'join_group_user_qty',
    selected_label: ''
});

/** 一天的时间戳 */
const ONE_DAY_TIME = 86400000;

/**
 * 当前选中的卡片
 */
const currentTabItem = computed(() => {
    return props.chartInfo.find(item => item.field_key === form.selected_quota);
});

/**
 * tab类型切换事件
 */
const onTabItem = (item: any) => {
    if (item.field_key === form.selected_quota) {
        return;
    }

    form.selected_quota = item.field_key;
    form.selected_label = item.field_name;
    getLineInfo();
};

// 时间范围： 7.11日之后可以选， 90天范围, 当天不可选
const disabledDate = (time: any) => {
    if (!pickDay.value) {
        return time.getTime() >= Date.now() - ONE_DAY_TIME || time.getTime() <= ONLINE_TIME;
    }
    const con1 = new Date(pickDay.value).getTime() - 89 * ONE_DAY_TIME;
    const con2 = new Date(pickDay.value).getTime() + 89 * ONE_DAY_TIME;
    // 时间区间的禁用
    const rangeDisabel = time.getTime() < con1 || time.getTime() > con2;

    // 时间区间的禁用 || 不能小于上线的日期 || 不能是今天
    return rangeDisabel || time.getTime() <= ONLINE_TIME || time.getTime() >= Date.now() - ONE_DAY_TIME;
};

/**
 * 时间变动
 */
const handleTimeChange = (val: any) => {
    if (!val) {
        pickDay.value = '';
        return;
    }
    emit('change-date', form.screen_time_range);
    getLineInfo();
};

const calendarChange = (val: Date[]) => {
    const [pointDay] = val;
    pickDay.value = pointDay;
};

// 获取折线图数据
const getLineInfo = async () => {
    xData.value = [];
    yData.value = [];
    const res: any = await getCustomerGroupLineChart(form);
    const list: any = res || [];
    if (list.length) {
        isShoweCharts.value = true;
        nextTick(() => {
            list.map((item: any, index) => {
                xData.value.push(item.date);
                yData.value.push(item.num);
            });
        });
    } else {
        isShoweCharts.value = false;
    }
};

/**
 * 折线图echarts渲染
 */
const getEchart = () => {
    const myChart = echarts.init(myRef.value);
    myChart.setOption({
        title: {
            subtext: currentTabItem.value.unit,
            top: -10,
            left: 16
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    show: false
                }
            },
            formatter: function (params: any) {
                let date = params[0].name;
                for (let i = 0, l = params.length; i < l; i++) {
                    const item = params[i];
                    date += `
                        <br/>${item.marker}${item.seriesName}
                        <b style="font-weight: 700;">${item.value}${currentTabItem.value.unit}</b>
                    `;
                }
                return date;
            }
        },
        grid: {
            x: 40,
            y: 50,
            x2: 40,
            y2: 40
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xData.value,
            axisLabel: {
                margin: 20
            }
        },
        yAxis: {
            type: 'value',
            minInterval: !['%', '元'].includes(currentTabItem.value.unit) ? 1 : undefined
        },
        series: [
            {
                name: form.selected_label,
                data: yData.value,
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 0,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#F8DCD1' },
                            { offset: 0.5, color: '#FDF8F6' },
                            { offset: 1, color: '#FFFAF9' }
                        ])
                    }
                },
                itemStyle: {
                    normal: {
                        borderWidth: 2,
                        color: '#FF9D23'
                    }
                },
                emphasis: {
                    // 鼠标 hover 时的样式
                    itemStyle: {
                        color: '#FF9D23', // hover 圆点颜色
                        borderColor: '#FF9D23', // hover 圆点边框颜色
                        borderWidth: 8
                    }
                }
            }
        ]
    });
    nextTick(() => {
        myChart.resize();
    });
    window.onresize = function () {
        myChart.resize();
    };
};
/**
 * @description: 监听x轴数据变化，有数据时渲染echarts
 * @return {*}
 */
watch(
    () => xData.value,
    val => {
        if (val.length) {
            nextTick(() => {
                getEchart();
            });
        }
    },
    { deep: true }
);

/* ----------------------------列卡片-start---------------------------- */
/**
 * 打开数据概览配置列弹窗
 */
const onSelectColumn = () => {
    emit('select-column');
};
/* ----------------------------列卡片-end---------------------------- */

defineExpose({
    searchLineInfo(key: string, label: string) {
        form.selected_quota = key;
        form.selected_label = label;
        getLineInfo();
    }
});
</script>

<style lang="scss" scoped>
@import './line-chart';
</style>
